package com.inspur.cloud.service.dataspace;

import com.inspur.cloud.configuration.AmbariConfig;
import com.inspur.cloud.exception.ApiException;
import com.inspur.cloud.util.SshConf;
import com.inspur.cloud.util.SshUtil;
import com.inspur.cloud.util.TConstants;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LinuxService {

    private static final Logger logger = LoggerFactory.getLogger(LinuxService.class);

    @Autowired
    ClusterConfigUtil clusterConfigUtil;
    @Autowired
    AmbariConfig ambariConfig;
    /**
     * 在Linux主机上增加租户和用户
     * @param user
     * @param group
     * @param flag 1增加 2删除
     * @return
     */
    public void operateUerAndGroupOnLinux(String user, String group, int flag) {
        operateUerAndGroupOnLinux(user, group, "", flag);
    }

    /**
     * 在Linux主机上增加租户和用户，添加用户时指定密码
     *
     * @param user
     * @param group
     * @param flag  1增加 2删除
     * @return
     */
    public void operateUerAndGroupOnLinux(String user, String group, String password, int flag) {
        List<String> hostNameList = clusterConfigUtil.getHostsConfig();
        if (null == hostNameList || hostNameList.isEmpty()) {
            throw new ApiException("Getting cluster hosts failed ！");
        }
        if (!operateUerAndGroup(hostNameList, user, group, password, flag)) {
            throw new ApiException("operateUerAndGroup failed ！");
        }
    }

    /**
     * 在集群每台机器上添加/删除用户，添加用户时指定密码
     *
     * @param hostNameList 主机列表
     * @param userId       用户
     * @param groupId      所属组
     * @param pwd          密码
     * @param flag         操作标识  1添加  2删除
     * @return
     */
    public boolean operateUerAndGroup(List<String> hostNameList, String userId, String groupId, String pwd, int flag) {

        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(groupId)) {
            return false;
        }
        try {
            String port = ambariConfig.getSshPort();
            String attachGroup = TConstants.KERBEROS_ATTACH_GROUP;
            String ambariServerHost = clusterConfigUtil.getAmbariServerHost();
            SshUtil sshUtil = remoteIp(ambariServerHost);
            //创建用户和组别
            for (int i = 0; i < hostNameList.size(); i++) {
                String host = hostNameList.get(i);
                if (flag == 1) {//增加
                    // 在集群的各个主机上执行命令
                    String cmdAddGroup = String.format("ssh -p %s -l root %s groupadd -f %s", port, host, groupId);
                    String cmdAddGroupBIGDATA = String.format("ssh -p %s -l root %s groupadd -f %s", port, host, attachGroup);
                    String cmdAddUser = String.format("ssh -p %s -l root %s useradd -m %s -g %s -G %s", port, host, userId, groupId, attachGroup);
                    // 远程SSH到其它节点修改用户密码
                    String cmdPasswdUser = String.format("echo %s | ssh -p %s -l root %s passwd --stdin %s", pwd, port, host, userId);

                    try {
                        sshUtil.runCmd(cmdAddGroupBIGDATA);
                        logger.info("--cmdAddGroup--" + cmdAddGroup);
                        sshUtil.runCmd(cmdAddGroup);
                        logger.info("--cmdAddUser--" + cmdAddUser);
                        sshUtil.runCmd(cmdAddUser);
                        if (!(pwd == null || pwd.equals(""))) {
                            logger.info("--cmdPasswdUser--");
                            sshUtil.runCmd(cmdPasswdUser);
                        }
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                    }
                } else if (flag == 2) { //删除
                    // 在集群的各个主机上执行命令
                    String cmdDelUser = String.format("ssh -p %s -l root %s userdel -f %s", port, host, userId);
                    logger.info("--cmdDelUser:" + cmdDelUser);
                    sshUtil.runCmd(cmdDelUser, "UTF-8");
                    if (!ambariConfig.isReserveLinuxHomeDir()) {
                        String cmdDelUserHome = String.format("ssh -p %s -l root %s rm -rf %s", port, host, "/home/"+userId);
                        logger.info("--cmdDelUserHome:" + cmdDelUser);
                        sshUtil.runCmd(cmdDelUserHome, "UTF-8");
                    }
                }
            }
        } catch (Exception e) {
            logger.error("Function--addUerAndGroup()--Failed:" + e.getMessage());
            throw new ApiException("LinuxService operateUerAndGroup error.");
        }
        return true;
    }

    /**
     * 修改Linux系统用户的密码
     *
     * @param user
     * @param newPassword
     */
    public void changeLinuxUserPassword(String user, String newPassword) {
        List<String> hostNameList = clusterConfigUtil.getHostsConfig();
        if (null == hostNameList || hostNameList.isEmpty()) {
            throw new ApiException("Getting cluster hosts failed ！");
        }
        if (StringUtils.isEmpty(user)) {
            throw new ApiException("changeLinuxUserPassword user is null.");
        }
        try {
            String serverHost = clusterConfigUtil.getAmbariServerHost();
            SshUtil sshUtil = remoteIp(serverHost);
            String cmdChangePwd = String.format("echo %s | passwd --stdin %s", newPassword, user);
            logger.info("changeLinuxUserPassword host[" + serverHost + "]");
            sshUtil.runCmd(cmdChangePwd);
            for (int i = 0; i < hostNameList.size(); i++) {
                String host = hostNameList.get(i);
                if (host.equals(serverHost)) {
                    continue;
                }
                cmdChangePwd = String.format("echo %s | ssh -l root %s passwd --stdin %s", newPassword, host, user);
                logger.info("changeLinuxUserPassword host[" + host + "]");
                sshUtil.runCmd(cmdChangePwd);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ApiException("LinuxService changeLinuxUserPassword error.");
        }
    }

    /**
     * 根据用户判断Linux系统中是否已存在该用户
     *
     * @param user
     * @return
     */
    public boolean isLinuxUserExist(String user) {
        String serverHost = clusterConfigUtil.getAmbariServerHost();
        boolean result = false;
        if (StringUtils.isEmpty(user)) {
            return result;
        }
        try {
            SshUtil sshUtil = remoteIp(serverHost);
            String cmdLinuxUserExists = "id -u " + user;
            String returnInfo = sshUtil.runCmdWithReturnInfo(cmdLinuxUserExists, "UTF-8");
            if (!returnInfo.contains("no such user")) {
                result = true;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ApiException("LinuxService isLinuxUserExit error.");
        }
        return result;
    }

    /**
     * SSH连接远程机器
     *
     * @param hostName
     * @return
     * @throws Exception
     */
    public SshUtil remoteIp(String hostName) throws Exception {
        // ssh远程连接kerberos服务器
        SshConf conf = new SshConf();
        conf.setHost(hostName);
        logger.info("--LinuxService RemoteIp SERVER_IP--:" + hostName);
        conf.setPort(Integer.parseInt(ambariConfig.getSshPort()));
        conf.setUsername(ambariConfig.getAmbariServerLoginUser());
//        conf.setPassword(ambariConfig.getAmbariServerLoginPass());
        SshUtil sshUtil = new SshUtil(conf); // 连接服务器
        return sshUtil;
    }
}
